<?php

namespace App\Admin\Repositories;

use App\Models\FirmBrand as Model;
use Dcat\Admin\Form;
use Dcat\Admin\Repositories\EloquentRepository;

class FirmBrand extends EloquentRepository
{
    /**
     * Model.
     *
     * @var string
     */
    protected $eloquentClass = Model::class;

    public function store(Form $form)
    {

        $updates = $form->updates();

        if ($updates['consult_time']>0 && $updates['consult_time']>time()){
            $updates['is_warn'] = 1;
        }


        $brand = Model::query()->create($updates);

        $brand->profile()->create($updates['profile']);

        return $brand->getKey();
    }


    public function update(Form $form)
    {
        $updates = $form->updates();


        if ($updates['consult_time']>0 && $updates['consult_time']>time()){
            $updates['is_warn'] = 1;
        }


        $brand = Model::query()->with('profile')->where('id',$form->getKey())->first();


        foreach ($brand->getFillable() as $value){
            if (isset($updates[$value])){
                $brand->{$value} = $updates[$value];
            }
        }

        $brand->save();



        if (empty($brand->profile)){
            $updates['profile']['brand_id'] = $brand->getKey();
            \App\Models\FirmBrandProfile::query()->create($updates['profile']);
        }else{
            foreach ($brand->profile->getFillable() as $item){

                if (isset($updates['profile'][$item])){
                    $brand->profile->{$item} = $updates['profile'][$item];
                }

            }

            $brand->profile->save();

        }




        return true;
    }
}
